<template>
  <div class="login-container">
    <div class="login-content">
      <el-card class="login-card">
        <div class="login-header">
          <img src="/logo.svg" alt="logo" class="logo" />
          <h2 class="title">鱼皮接口</h2>
          <p class="subtitle">API 开放平台</p>
        </div>

        <el-form
          ref="formRef"
          :model="form"
          :rules="currentRules"
          class="login-form"
          @submit.prevent="handleSubmit"
        >
          <el-tabs v-model="activeTab" centered>
            <el-tab-pane label="登录" name="login">
              <el-tabs v-model="loginType" centered>
                <el-tab-pane label="账户密码登录" name="account">
                  <el-form-item prop="userAccount">
                    <el-input
                      v-model="form.userAccount"
                      placeholder="用户名: admin or user"
                      size="large"
                    >
                      <template #prefix>
                        <el-icon><User /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="userPassword">
                    <el-input
                      v-model="form.userPassword"
                      type="password"
                      placeholder="密码: ant.design"
                      size="large"
                      show-password
                    >
                      <template #prefix>
                        <el-icon><Lock /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                </el-tab-pane>

                <el-tab-pane label="手机号登录" name="mobile">
                  <el-form-item prop="mobile">
                    <el-input
                      v-model="form.mobile"
                      placeholder="请输入手机号！"
                      size="large"
                    >
                      <template #prefix>
                        <el-icon><Iphone /></el-icon>
                      </template>
                    </el-input>
                  </el-form-item>
                  <el-form-item prop="captcha">
                    <div class="captcha-container">
                      <el-input
                        v-model="form.captcha"
                        placeholder="请输入验证码！"
                        size="large"
                      >
                        <template #prefix>
                          <el-icon><Lock /></el-icon>
                        </template>
                      </el-input>
                      <el-button
                        :disabled="captchaCountdown > 0"
                        @click="getCaptcha"
                        class="captcha-btn"
                      >
                        {{ captchaCountdown > 0 ? `${captchaCountdown}秒后重新获取` : '获取验证码' }}
                      </el-button>
                    </div>
                  </el-form-item>
                </el-tab-pane>
              </el-tabs>

              <div class="login-options">
                <el-checkbox v-model="form.autoLogin">自动登录</el-checkbox>
                <a href="#" class="forgot-password">忘记密码 ?</a>
              </div>

              <el-button
                type="primary"
                size="large"
                class="submit-btn"
                :loading="loading"
                @click="handleSubmit"
              >
                登录
              </el-button>

              <div class="other-login">
                <span>其他登录方式 :</span>
                <el-button circle class="social-btn">
                  <el-icon><ChatDotRound /></el-icon>
                </el-button>
                <el-button circle class="social-btn">
                  <el-icon><Star /></el-icon>
                </el-button>
              </div>
            </el-tab-pane>

            <el-tab-pane label="注册" name="register">
              <el-form-item prop="userAccount">
                <el-input
                  v-model="form.userAccount"
                  placeholder="请输入用户名"
                  size="large"
                >
                  <template #prefix>
                    <el-icon><User /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="userPassword">
                <el-input
                  v-model="form.userPassword"
                  type="password"
                  placeholder="请输入密码"
                  size="large"
                  show-password
                >
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="checkPassword">
                <el-input
                  v-model="form.checkPassword"
                  type="password"
                  placeholder="请确认密码"
                  size="large"
                  show-password
                >
                  <template #prefix>
                    <el-icon><Lock /></el-icon>
                  </template>
                </el-input>
              </el-form-item>

              <el-button
                type="primary"
                size="large"
                class="submit-btn"
                :loading="loading"
                @click="handleSubmit"
              >
                注册
              </el-button>
            </el-tab-pane>
          </el-tabs>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Iphone, ChatDotRound, Star } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { userRegisterUsingPOST } from '@/api/user'

const router = useRouter()
const userStore = useUserStore()

const formRef = ref()
const loading = ref(false)
const activeTab = ref('login')
const loginType = ref('account')
const captchaCountdown = ref(0)

const form = reactive({
  userAccount: '',
  userPassword: '',
  checkPassword: '',
  mobile: '',
  captcha: '',
  autoLogin: true
})

const loginRules = {
  userAccount: [
    { required: true, message: '用户名是必填项！', trigger: 'blur' }
  ],
  userPassword: [
    { required: true, message: '密码是必填项！', trigger: 'blur' }
  ],
  mobile: [
    { required: true, message: '手机号是必填项！', trigger: 'blur' },
    { pattern: /^1\d{10}$/, message: '不合法的手机号！', trigger: 'blur' }
  ],
  captcha: [
    { required: true, message: '验证码是必填项！', trigger: 'blur' }
  ]
}

const registerRules = {
  userAccount: [
    { required: true, message: '用户名是必填项！', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名长度在 4 到 20 个字符', trigger: 'blur' }
  ],
  userPassword: [
    { required: true, message: '密码是必填项！', trigger: 'blur' },
    { min: 8, max: 20, message: '密码长度在 8 到 20 个字符', trigger: 'blur' }
  ],
  checkPassword: [
    { required: true, message: '请确认密码！', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== form.userPassword) {
          callback(new Error('两次输入的密码不一致！'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 根据当前标签页动态生成验证规则
const currentRules = computed(() => {
  if (activeTab.value === 'register') {
    return registerRules
  }
  
  return loginType.value === 'account' 
    ? { userAccount: loginRules.userAccount, userPassword: loginRules.userPassword }
    : { mobile: loginRules.mobile, captcha: loginRules.captcha }
})

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
    if (activeTab.value === 'register') {
      // 注册逻辑
      const registerData = {
        userAccount: form.userAccount,
        userPassword: form.userPassword,
        checkPassword: form.checkPassword
      }
      
      const result = await userRegisterUsingPOST(registerData)
      
      if (result.code === 0) {
        ElMessage.success('注册成功！请登录')
        // 注册成功后切换到登录页面
        activeTab.value = 'login'
        // 清空表单
        form.userAccount = ''
        form.userPassword = ''
        form.checkPassword = ''
        formRef.value.resetFields()
      } else {
        ElMessage.error(result.message || '注册失败')
      }
    } else {
      // 登录逻辑
      const loginData = loginType.value === 'account' 
        ? { userAccount: form.userAccount, userPassword: form.userPassword }
        : { mobile: form.mobile, captcha: form.captcha }
      
      const result = await userStore.login(loginData)
      
      if (result.success) {
        ElMessage.success('登录成功')
        const redirect = new URLSearchParams(window.location.search).get('redirect') || '/'
        router.push(redirect)
      } else {
        ElMessage.error(result.message || '登录失败')
      }
    }
  } catch (error) {
    console.error('操作错误:', error)
    ElMessage.error('请检查输入信息')
  } finally {
    loading.value = false
  }
}

const getCaptcha = async () => {
  if (!form.mobile) {
    ElMessage.warning('请先输入手机号')
    return
  }
  
  try {
    // 这里应该调用获取验证码的API
    captchaCountdown.value = 60
    const timer = setInterval(() => {
      captchaCountdown.value--
      if (captchaCountdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
    
    ElMessage.success('获取验证码成功！验证码为：1234')
  } catch (error) {
    ElMessage.error('获取验证码失败')
  }
}
</script>

<style scoped lang="scss">
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-content {
  width: 100%;
  max-width: 400px;
}

.login-card {
  border-radius: 8px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
  
  .logo {
    width: 64px;
    height: 64px;
    margin-bottom: 16px;
  }
  
  .title {
    font-size: 24px;
    font-weight: 600;
    color: #333;
    margin: 0 0 8px 0;
  }
  
  .subtitle {
    font-size: 14px;
    color: #666;
    margin: 0;
  }
}

.login-form {
  .captcha-container {
    display: flex;
    gap: 12px;
    
    .captcha-btn {
      width: 120px;
      flex-shrink: 0;
    }
  }
  
  .login-options {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 24px 0;
    
    .forgot-password {
      color: #409eff;
      text-decoration: none;
      
      &:hover {
        text-decoration: underline;
      }
    }
  }
  
  .submit-btn {
    width: 100%;
    margin-bottom: 24px;
  }
  
  .other-login {
    text-align: center;
    
    span {
      color: #666;
      margin-right: 12px;
    }
    
    .social-btn {
      margin: 0 4px;
    }
  }
}
</style>
